package com.ng.sys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.ng.sys.model.domain.*;
import com.ng.sys.service.IDict;

import cn.hutool.core.collection.CollectionUtil;

@Service
public class DictImpl implements IDict {

	@Override
	public List<DictItem> listItemOptions(String typeCode) {
		List<DictItem> options = DictItem.dao.find("select * from " + DictItem.TABLE_NAME
				+ " where dict_id in ( select id from " + Dict.TABLE_NAME + " where code=? ) order by sort asc ",
				typeCode);
		return options;
	}

	@Override
	public List<Dict> list(String keywords) {
		
		String _sql = "select * from " + Dict.TABLE_NAME + " where 1=1 ";

		if (!StrKit.isBlank(keywords)) {
			_sql += " and name like '%" + keywords + "%' ";
		}
		_sql += " order by sort asc";

		List<Dict> depts = Dict.dao.find(_sql);

		Set<String> parentIds = depts.stream().map(Dict::getParentId).collect(Collectors.toSet());

		Set<String> menuIds = depts.stream().map(Dict::getId).collect(Collectors.toSet());

		List<String> rootIds = CollectionUtil.subtractToList(parentIds, menuIds); // 求差集，得到 parentIds 中 menuIds 没有的元素

		List<Dict> list = new ArrayList<Dict>();
		for (String rootId : rootIds) {
			list.addAll(recurDicts(rootId, depts)); // 递归
		}

		return list;
	}

	private List<Dict> recurDicts(String rootId, List<Dict> depts) {
		return CollectionUtil.emptyIfNull(depts).stream().filter(menu -> menu.getParentId().equals(rootId))
				.map(entity -> {
					List<Dict> children = recurDicts(entity.getId(), depts);
					entity.setChildren(children);
					return entity;
				}).collect(Collectors.toList());
	}

	@Override
	public List<Dict> listOptions(String keywords,String id) {
		String _sql = "select * from " + Dict.TABLE_NAME + " where 1=1 ";

		if (!StrKit.isBlank(keywords)) {
			_sql += " and (name like '%" + keywords + "%' or code like '%"+keywords+"%') ";
		}
		
		if (!StrKit.isBlank(id)) {
			_sql += " and id='"+id+"' ";
		}
		_sql += " order by sort asc";
        return Dict.dao.find(_sql);
	}
	
	
	@Override
	public boolean delete(String id) {
		deleteChildrens(id);
		Db.delete("delete from "+Dict.TABLE_NAME+" where id=?",id);
		Db.delete("delete from "+DictItem.TABLE_NAME+" where dict_id=?",id);
        return true;
	}
	
	private void deleteChildrens(String id) {
		List<Dict> menus=Dict.dao.find("select id from "+Dict.TABLE_NAME+" where parent_id=?",id);
		for(Dict menu:menus) {
			deleteChildrens(menu.getId());
			menu.delete();
			Db.delete("delete from "+DictItem.TABLE_NAME+" where dict_id=?",id);
		}
	}

}
